<template>
  <div class="opportunity-detail">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>机会线索详情</span>
          <el-button @click="handleBack">返回</el-button>
        </div>
      </template>

      <!-- 基本信息 -->
      <div class="section">
        <h3>基本信息</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="ID">{{ opportunity.id }}</el-descriptions-item>
          <el-descriptions-item label="客户名称">
            {{ opportunity.customer_name }}
          </el-descriptions-item>
          <el-descriptions-item label="客户类型">
            <el-tag v-if="opportunity.customer_type === 1" type="info">个人</el-tag>
            <el-tag v-else type="success">企业</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="联系人">
            {{ opportunity.contact_name || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="联系人电话">
            {{ opportunity.contact_phone || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="线索类别">
            <el-tag v-if="opportunity.category === 1" type="danger">案件委托</el-tag>
            <el-tag v-else-if="opportunity.category === 2" type="warning">法务需求</el-tag>
            <el-tag v-else type="primary">法务专项</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="线索等级">
            <el-tag v-if="opportunity.level === 1" type="danger">A级-本月内可签约</el-tag>
            <el-tag v-else-if="opportunity.level === 2" type="warning">B级-30天内可签约</el-tag>
            <el-tag v-else type="info">C级-持续跟进</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag v-if="opportunity.status === 1" type="success">有效</el-tag>
            <el-tag v-else-if="opportunity.status === 2" type="info">已转化</el-tag>
            <el-tag v-else type="danger">已失效</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="发现日期">
            {{ formatDate(opportunity.discovery_date) }}
          </el-descriptions-item>
          <el-descriptions-item label="负责人">{{ opportunity.user_name }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatDateTime(opportunity.create_time) }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间">
            {{ formatDateTime(opportunity.update_time) }}
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 线索描述 -->
      <div class="section" v-if="opportunity.description">
        <h3>线索描述</h3>
        <div class="description">{{ opportunity.description }}</div>
      </div>

      <!-- 操作按钮 -->
      <div class="actions">
        <el-button v-if="opportunity.status === 1" type="primary" @click="handleConvert">
          转化为订单
        </el-button>
        <el-button @click="handleEdit">编辑</el-button>
        <el-button @click="handleAddFollowup">添加跟进</el-button>
      </div>

      <!-- 跟进记录 -->
      <div class="section">
        <h3>跟进记录</h3>
        <el-timeline>
          <el-timeline-item
            v-for="followup in followups"
            :key="followup.id"
            :timestamp="formatDateTime(followup.create_time)"
            placement="top"
          >
            <el-card>
              <div class="followup-item">
                <div class="followup-header">
                  <span class="followup-type">
                    {{ followup.followup_type === 1 ? '电话跟进' : '其他' }}
                  </span>
                  <span class="followup-user">{{ followup.user_name }}</span>
                </div>
                <div class="followup-content">{{ followup.content }}</div>
                <div class="followup-time">
                  跟进时间：{{ formatDateTime(followup.followup_time) }}
                </div>
                <div class="next-followup-time" v-if="followup.next_followup_time">
                  下次跟进时间：{{ formatDateTime(followup.next_followup_time) }}
                </div>
              </div>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-card>

    <!-- 跟进对话框 -->
    <el-dialog v-model="followupDialogVisible" title="添加跟进记录" width="600px">
      <el-form :model="followupForm" label-width="120px">
        <el-form-item label="跟进方式">
          <el-radio-group v-model="followupForm.followup_type">
            <el-radio :label="1">电话</el-radio>
            <el-radio :label="2">微信</el-radio>
            <el-radio :label="3">面谈</el-radio>
            <el-radio :label="4">邮件</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="跟进结果">
          <el-radio-group v-model="followupForm.followup_result">
            <el-radio :label="1">有进展</el-radio>
            <el-radio :label="2">待考虑</el-radio>
            <el-radio :label="3">无进展</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="跟进时间">
          <el-date-picker
            v-model="followupForm.followup_time"
            type="datetime"
            placeholder="选择日期时间"
            style="width: 100%"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="跟进内容">
          <el-input
            v-model="followupForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入跟进内容"
          />
        </el-form-item>
        <el-form-item label="下次跟进时间">
          <el-date-picker
            v-model="followupForm.next_followup_time"
            type="datetime"
            placeholder="选择日期时间"
            style="width: 100%"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="followupDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitFollowup">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted } from 'vue'
  import { useRouter, useRoute } from 'vue-router'
  import { ElMessage, ElMessageBox } from 'element-plus'

  // 类型定义
  interface Opportunity {
    id: number
    customer_name: string
    customer_type: number
    contact_name?: string
    contact_phone?: string
    category: number
    level: number
    status: number
    discovery_date: number | string
    user_name: string
    create_time: number | string
    update_time: number | string
    description?: string
  }

  interface Followup {
    id: number
    followup_type: number
    user_name: string
    content: string
    followup_result: number
    followup_time: number | string
    next_followup_time?: number | string
    create_time: number | string
  }

  const router = useRouter()
  const route = useRoute()

  // 机会线索详情
  const opportunity = ref<Opportunity>({} as Opportunity)
  const followups = ref<Followup[]>([])

  // 跟进对话框
  const followupDialogVisible = ref(false)
  const followupForm = ref({
    followup_type: 1,
    followup_result: 1,
    followup_time: '',
    content: '',
    next_followup_time: '',
  } as {
    followup_type: number
    followup_result: number
    followup_time: string
    content: string
    next_followup_time: string
  })

  // 初始化
  onMounted(() => {
    const id = route.params.id
    fetchDetail(id as string)
  })

  // 获取详情
  const fetchDetail = async (id: string) => {
    try {
      // TODO: 调用API获取详情
      // const response = await fetchOpportunityDetail(id)
      // opportunity.value = response
      // followups.value = response.followups || []
    } catch (error) {
      console.error(error)
      ElMessage.error('获取详情失败')
    }
  }

  // 返回
  const handleBack = () => {
    router.go(-1)
  }

  // 编辑
  const handleEdit = () => {
    router.push(`/crm/opportunity/edit/${opportunity.value.id}`)
  }

  // 转化为订单
  const handleConvert = async () => {
    try {
      await ElMessageBox.confirm('确定要将此线索转化为订单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      // TODO: 调用API转化
      ElMessage.success('转化成功，请前往订单模块创建订单')
      fetchDetail(route.params.id as string)
    } catch (error) {
      console.log('用户取消')
    }
  }

  // 添加跟进
  const handleAddFollowup = () => {
    followupDialogVisible.value = true
  }

  // 提交跟进
  const handleSubmitFollowup = async () => {
    try {
      // TODO: 调用API添加跟进记录
      ElMessage.success('添加跟进成功')
      followupDialogVisible.value = false
      fetchDetail(route.params.id as string)
    } catch (error) {
      ElMessage.error('添加失败')
    }
  }

  // 格式化日期
  const formatDate = (timestamp: number | string) => {
    if (!timestamp) return ''
    const date = new Date(
      typeof timestamp === 'string' ? parseInt(timestamp) * 1000 : timestamp * 1000
    )
    return date.toLocaleDateString()
  }

  const formatDateTime = (timestamp: number | string) => {
    if (!timestamp) return ''
    const date = new Date(
      typeof timestamp === 'string' ? parseInt(timestamp) * 1000 : timestamp * 1000
    )
    return date.toLocaleString()
  }
</script>

<style lang="scss" scoped>
  .opportunity-detail {
    padding: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .section {
      margin-bottom: 30px;

      h3 {
        margin-bottom: 15px;
        font-size: 16px;
        font-weight: bold;
      }
    }

    .description {
      padding: 15px;
      background: #f5f5f5;
      border-radius: 4px;
      line-height: 1.6;
    }

    .actions {
      margin-bottom: 30px;
      display: flex;
      gap: 10px;
    }

    .followup-item {
      .followup-header {
        display: flex;
        justify-content: space-between;
        margin-bottom: 10px;

        .followup-type {
          font-weight: bold;
        }

        .followup-user {
          color: #666;
        }
      }

      .followup-content {
        margin-bottom: 10px;
        line-height: 1.6;
      }

      .followup-result,
      .followup-time,
      .next-followup-time {
        font-size: 14px;
        color: #666;
        margin-bottom: 5px;
      }
    }
  }
</style>
